﻿using LightCAD.Core;
using LightCAD.Runtime;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;

namespace LightCAD.Drawing
{
    public class PointInputer : Inputer
    {
        private Vector2d? inputp;
        private Vector2d? extInputp;
        private string option;
        public PointInputer(DocumentRuntime docRt)  : base(docRt)
        {
        }
        public async Task<InputResult> Execute(string prompt)
        {
            inputp = null;
            option = null;
            this.vportRt.SnapRt = new SnapRuntime(this.vportRt);
            var vportRt=this.docRt.DrawingEditRt.ActiveViewportRt;
            vportRt.CursorType = LcCursorType.InputPoint;
            this.Reset();
            this.AttachEvents();
            Prompt(prompt);
            await WaitFinish();
            this.DetachEvents();
           
            vportRt.CursorType = LcCursorType.SelectElement;
            this.vportRt.SnapRt = null;
            if (this.isCancelled)
                return null;
            else
            {
                return new InputResult(inputp, option) { Extent = this.extInputp };
            }
        }
        
        protected override void OnViewportMouseMove(MouseEventRuntime e)
        {
            var mp = this.vportRt.ConvertScrToWcs(e.Location.ToVector2d());
            this.vportRt.SnapRt.MouseMove(mp);
        }
        protected override void OnViewportMouseHoverStart(MouseEventRuntime e)
        {
            var mp = this.vportRt.ConvertScrToWcs(e.Location.ToVector2d());
            this.vportRt.SnapRt.MouseHover(mp);
        }
        protected override void OnViewportMouseDown(MouseEventRuntime e)
        {            //这里要返回世界坐标，因为开启捕捉之后，就没有屏幕坐标了
            this.inputp = this.vportRt.ConvertScrToWcs(e.Location.ToVector2d());
            if (this.vportRt.SnapRt.Current != null)
            {
                this.extInputp = this.inputp;
                this.inputp = this.vportRt.SnapRt.Current.SnapPoint;
            }
            docRt.CommandCtrl.WriteInfo(docRt.CommandCtrl.GetPrompt());
            this.Finish();
        }

        protected override void OnInputBoxKeyDown(KeyEventRuntime e)
        {
            base.OnInputBoxKeyDown(e);
            if (e.KeyCode == 13 || e.KeyCode==32)//Keys.Enter
            {
                var text = docRt.CommandCtrl.GetInputText().Trim();
                docRt.CommandCtrl.SetInputText(string.Empty);
                //TODO:检查可以输入的字符
                this.inputp = InputUtils.ParsePoint(text);
                if (this.inputp == null)
                {
                    this.option = text;
                    if(this.option == string.Empty)
                    {
                        this.option = " ";
                    }
                }
               
                this.Finish();
            }
           
        }
    }
}
